import { Injectable, OnDestroy } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, Router, RouterStateSnapshot } from '@angular/router';
import { AuthService } from '../services/auth.service';
import { Observable } from 'rxjs';
import { AppRoutingModule } from '../app-routing.module';

/**
 * 路由处理
 */
@Injectable({
    providedIn: 'root'
})
export class RouterGuard implements CanActivate,OnDestroy {

    intervalId:any;
    constructor(private _authService: AuthService, private _router: Router,private appRoutingModule:AppRoutingModule) {
    }

    /**
     * 判断用户是否具有权限进入页面
     * @returns Observable<boolean>
     */
    canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> {
        let url = '';
        if (state.url.includes('?')) {
            url = state.url.substring(0, state.url.lastIndexOf('?'));
        } else {
            url = state.url;
        }
        if (url.includes('manage')) {
            if (localStorage.getItem('token') !== null) {
                //等待菜单加载完成后，进入页面
                this.startLoop(state.url);
                return;
            } else {
                this._router.navigateByUrl('/login').then();
            }
        }
    }


    startLoop(url:string) {
        if (this.appRoutingModule.menusMap.size == 0){
            this.intervalId = setInterval(() => {
                console.log('router waiting menu load')
                if (this.appRoutingModule.menusMap.size != 0) {
                    console.log(this.appRoutingModule.allRoutes)
                    this.stopLoop();
                    this._router.navigate([this._router.url],{}).finally();
                }
            }, 5000);
        }
    }

    stopLoop() {
        console.log("intervalId",this.intervalId)
        if (this.intervalId) {
            clearInterval(this.intervalId);
            this.intervalId = null;
            console.log('router end menu load')
        }
    }

    ngOnDestroy(): void {
        this.stopLoop();
    }
}
